const debug = require('debug')('tpgj')
const md5 = require('blueimp-md5')

module.exports = async function(ctx, next) {
  try {

    const timestamp = ctx.request.body.timestamp || ctx.query.timestamp,
      { authcode } = ctx.header

    if (ctx.method === 'POST' && authcode !== md5(`${timestamp}tpgj`)) {
      ctx.body = { code: -1, msg: '非法请求' }
      return
    } else {
      await next()
    }

    ctx.body = ctx.body ? ctx.body : {
      code: 0,
      msg: '操作失败'
    }
  } catch (e) {

    debug('Catch Error: %o', e)

    ctx.status = 200

    ctx.body = {
      code: 0,
      msg: e && e.message ? e.message : e.toString()
    }
  }
}